#include "samples.h"

SHELL_CMD_FN(_os_sample_pipe);

SHELL_REGISTER_CMD(
    register_sample_pipe,
    SHELL_SETUP_CMD("sample-pipe", "OS API example of: pipe", _os_sample_pipe, NULL), //
);

#define PIPE_SIZE 100

struct sample_struct
{
    uint8_t index;
    uint32_t data;
};

static os_pipe_t s_pipe_handle;

SHELL_CMD_FN(_os_sample_pipe)
{
    tag();

    uint8_t buf[10];
    uint8_t byte;
    uint32_t word;
    size_t write_bytes;
    size_t read_bytes;

    for (int i = 0; i < sizeof(buf); i++)
    {
        buf[i] = i;
    }

    do
    {
        printf("create a pipe object\r\n");
        if (os_pipe_create(&s_pipe_handle, PIPE_SIZE) != OS_OK)
        {
            break;
        }

        printf("fill 1 byte into the pipe object\r\n");
        write_bytes = os_pipe_poll_write(&s_pipe_handle, 0x11);
        if (write_bytes != 1)
        {
            break;
        }
        printf("success to written %d byte\r\n", write_bytes);

        printf("fill datas into the pipe object\r\n");
        write_bytes = os_pipe_fifo_fill(&s_pipe_handle, buf, sizeof(buf));
        if (write_bytes != sizeof(buf))
        {
            break;
        }
        printf("success to written %d bytes\r\n", write_bytes);

        printf("read 1 byte from the pipe object\r\n");
        read_bytes = os_pipe_poll_read(&s_pipe_handle, &byte);
        if (read_bytes != 1)
        {
            break;
        }
        printf("value = 0x%x\r\n", byte);

        printf("read 4 bytes from the pipe object\r\n");
        read_bytes = os_pipe_fifo_read(&s_pipe_handle, &word, sizeof(word));
        if (read_bytes != sizeof(word))
        {
            break;
        }
        printf("value = 0x%x\r\n", word);

        printf("read any length from the pipe object\r\n");
        read_bytes = os_pipe_fifo_read(&s_pipe_handle, buf, sizeof(buf));
        if (read_bytes != sizeof(buf) - sizeof(word))
        {
            break;
        }
        printf("success to read %d bytes\r\n", read_bytes);

        printf("objects can be deleted when they are no longer used\r\n");
        os_pipe_delete(&s_pipe_handle);

        printf("operate success\r\n");
        return 0;

    } while (0);

    os_pipe_delete(&s_pipe_handle);

    printf("operate fail!\r\n");
    return -1;
}
